package com.visionet.waveletData.web.web.account;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.visionet.waveletData.web.common.constant.MobileKey;
import com.visionet.waveletData.web.common.utilities.MessageSourceHelper;
import com.visionet.waveletData.web.entity.account.User;
import com.visionet.waveletData.web.service.account.AccountService;
import com.visionet.waveletData.web.service.business.ChatConnection;
import com.visionet.waveletData.web.web.BaseController;
import com.visionet.waveletData.web.webservice.rest.RestException;

@Controller
public class LoginRestController extends BaseController{
	
	private static Logger log = LoggerFactory.getLogger(LoginRestController.class);

	
	@Autowired
	private AccountService accountService;
//	@Autowired
//	private UserInfoService userInfoService;
	@Autowired
	private MessageSourceHelper messageSourceHelper;
//	@Autowired
//	private ResourceService resourceService;
	@Autowired
	private ChatConnection chatConnection;
	
	
	@RequestMapping(value = "/weblogin", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<?> weblogin(@RequestBody Map<String,String> mapUser) throws Exception {
		String username = mapUser.get("username");
		Map<String,String> map = GetSuccMap();
		try{
			UsernamePasswordToken token = new UsernamePasswordToken();
		    token.setUsername(username);  
		    token.setPassword(mapUser.get("password").toCharArray());  
			SecurityUtils.getSubject().login(token);

//			resourceService.updateLastLoginOn(getCurrentUserId(), DateUtil.getCurrentDate(),SysConstants.CLIENT_WEB);
			map.put("id", getCurrentUserId().toString());
			//更新最后登陆时间   
			User u = accountService.findUserInfoByUserId(getCurrentUserId());
			u.setLast_login_time(new Date());
			accountService.saveUser(u);
//			map.put("trueNameCheck",userInfoService.checkTrueNameDept(getCurrentUserId())+"");
			map.put("trueNameCheck",u.getUser_type());
			map.put("userName", getLoginUserName());
			
            if(isAppRole()){
                map.put("appFlag","1");
            }else{
                map.put("appFlag","0");
            }

			
		}catch(UnknownAccountException uae){
			log.error("weblogin UnknownAccount: "+uae.toString());
			throw new RestException(messageSourceHelper.getMessage("login.failure"));
		}catch(IncorrectCredentialsException ice){
			log.error("weblogin IncorrectCredentials: "+ice.toString());
			throw new RestException(messageSourceHelper.getMessage("login.failure"));
		}catch(Exception e){
			log.error("weblogin error: ",e);
			
			User user = accountService.findByLoginName(username);
//			if(user!=null&&user.getIsLock().equals(SysConstants.USER_ACTIVITY_DISABLED)){
//				throw new RestException(messageSourceHelper.getMessage("login.user.disabled"));
//			}
			
			throw new RestException(messageSourceHelper.getMessage("login.failure"));
		}
		
		
		return new ResponseEntity<Map<String,String>>(map ,HttpStatus.OK);
	}
	
	
	
	@RequestMapping(value = "/mobileErr", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<Map<String,String>> mobileErr(HttpServletRequest request) {
		
		Map<String,String> map = new HashMap<String,String>();
		map.put(MobileKey.CODE, (String)request.getAttribute(MobileKey.CODE));
		map.put(MobileKey.MSG, (String)request.getAttribute(MobileKey.MSG));
		
		return new ResponseEntity<Map<String,String>>(map ,HttpStatus.ACCEPTED);
	}
	
	@RequestMapping(value = "/mobileErr", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<Map<String,String>> mobileErrPost(HttpServletRequest request) {
		
		Map<String,String> map = new HashMap<String,String>();
		map.put(MobileKey.CODE, (String)request.getAttribute(MobileKey.CODE));
		map.put(MobileKey.MSG, (String)request.getAttribute(MobileKey.MSG));
		
		return new ResponseEntity<Map<String,String>>(map ,HttpStatus.ACCEPTED);
	}


    @RequestMapping(value = "/error/{code}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Map<String,String>> error(@PathVariable("code") String code) {

        Map<String,String> map = Maps.newHashMap();
        map.put(MobileKey.CODE, code);
        map.put(MobileKey.MSG, "system error!");

        HttpStatus status;
        if(code.equals("404")) {
            status = HttpStatus.NOT_FOUND;
        }else if(code.equals("403")){
            status = HttpStatus.FORBIDDEN;
        }else{
            status = HttpStatus.ACCEPTED;
        }
        return new ResponseEntity<Map<String,String>>(map ,status);
    }




  

}
